package edu.dayu.controller;

import com.alipay.api.response.AlipayTradeQueryResponse;
import edu.dayu.enums.PaymentTypeEnum;
import edu.dayu.result.Result;
import edu.dayu.service.AliPayService;
import edu.dayu.service.PaymentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/order/weixin")
public class AliPayController {
    @Autowired
    private AliPayService aliPayService;

    /**
     * 下单 生成二维码
     */
    @GetMapping("/createNative/{orderId}")
    public Result createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {
        return Result.ok(aliPayService.goAliPay(orderId));
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {
        //调用查询接口
        AlipayTradeQueryResponse response = aliPayService.queryPayStatus(orderId, PaymentTypeEnum.ALIPAY.name());
        if (response == null) {//出错
            return Result.fail().message("支付出错");
        }
        if ("Success".equals(response.getMsg())) {//如果成功
            //更改订单状态，处理支付结果
            String out_trade_no = response.getOutTradeNo();
            aliPayService.paySuccess(out_trade_no, PaymentTypeEnum.ALIPAY.getStatus(), response);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}
